import { useEventListener } from '@vueuse/core'

export function useWheelWithoutSynthetic(targetRef, eventHandler) {
  let timerId
  let prevTsp
  let lock
  const deltaHist = []

  useEventListener(targetRef, 'wheel', (evt) => {
    if (timerId) {
      clearTimeout(timerId)
    }
    timerId = setTimeout(() => (deltaHist.length = 0), 400)

    const { wheelDelta, wheelDeltaX, deltaX, deltaY, detail } = evt

    const currTsp = Date.now()
    const deltaVal = wheelDelta || -deltaY || -detail
    const hasDeltaX = void 0 !== wheelDeltaX || void 0 !== deltaX
    const isVertical = Math.abs(wheelDeltaX) < Math.abs(wheelDelta) || Math.abs(deltaX) < Math.abs(deltaY) || !hasDeltaX

    deltaHist.push(Math.abs(deltaVal))
    const tspElapsed = currTsp - prevTsp
    prevTsp = currTsp

    if (tspElapsed > 400 && deltaHist.length === 1) {
      deltaHist.push(deltaHist[0])
      lock = false
    }

    const pass = avarageLast(deltaHist, 20) > avarageLast(deltaHist, 40)

    if (pass && !lock && isVertical) {
      eventHandler(evt)
      lock = true
    }

    if (!pass && lock && isVertical) {
      lock = false
    }
  })
}

function avarageLast(arr, lastCount) {
  const total = arr.slice(Math.max(arr.length - lastCount, 1)).reduce((a, c) => a + c, 0)
  return Math.ceil(total / lastCount)
}
